#include <qfiledialog.h>
#include <qfile.h>
#include <qtextstream.h>
#include <QMessageBox>
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect( ui->inputPushButton, SIGNAL( clicked() ), this, SLOT( onInputClicked() ) );
    connect( ui->outputPushButton, SIGNAL( clicked() ), this, SLOT( onOutputClicked() ) );
    connect( ui->goPushButton, SIGNAL( clicked() ), this, SLOT( onGoClicked()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void MainWindow::onInputClicked()
{
   QFileDialog dlg(this);

   dlg.setFileMode(QFileDialog::ExistingFile);
   dlg.setNameFilter(tr("vCard file (*.vcf)"));
   dlg.setViewMode(QFileDialog::Detail);
   dlg.setAcceptMode(QFileDialog::AcceptOpen);

   if (dlg.exec())
   {
      QFileInfo inputFile(dlg.selectedFiles().at(0));

      ui->inputLineEdit->setText(inputFile.absoluteFilePath());
      ui->outputLineEdit->setText(QString(tr("%1/%2_android.%3")).arg(inputFile.absolutePath()).arg(inputFile.completeBaseName()).arg(inputFile.completeSuffix()));
   }
}

void MainWindow::onOutputClicked()
{
   QFileDialog dlg(this);

   dlg.setFileMode(QFileDialog::AnyFile);
   dlg.setNameFilter(tr("vCard file (*.vcf)"));
   dlg.setViewMode(QFileDialog::Detail);
   dlg.setAcceptMode(QFileDialog::AcceptSave);
   dlg.setDefaultSuffix(tr("vcf"));

   if (dlg.exec())
   {
      ui->outputLineEdit->setText(dlg.selectedFiles().at(0));
   }
}

void MainWindow::onGoClicked()
{
   QFile inFile(ui->inputLineEdit->text(), this);
   QFile outFile(ui->outputLineEdit->text(), this);

   if (inFile.open(QFile::ReadOnly))
   {
      if (outFile.open(QFile::WriteOnly))
      {
         QTextStream streamIn(&inFile);
         QTextStream streamOut(&outFile);
         QString line;

         while(!streamIn.atEnd())
         {           
            streamIn >> line;

            if (!line.compare(tr("PHOTO;BASE64:")))
            {
               line = tr("PHOTO;ENCODING=BASE64;JPEG:");
            }

            streamOut << line << endl;
         }
         outFile.close();

         QMessageBox::information(this, tr(""), tr("Done"), QMessageBox::Close);
      } else
      {
         QMessageBox::critical(this, tr("Error"), tr("unable to create output file"), QMessageBox::Close);
      }
      inFile.close();
   } else
   {
      QMessageBox::critical(this, tr("Error"), tr("unable to open input file"), QMessageBox::Close);
   }
}
